package cn.sdstudio.config;


import cn.sdstudio.entity.User;
import cn.sdstudio.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zyq
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CustomUserDetailsServiceImpl implements UserDetailsService {

    private final UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        log.info("尝试按用户名加载用户: {}", username);

        // 1. 查询用户
        User userEntity = userMapper.selectByUsername(username);
        if (userEntity == null) {
            log.warn("User not found with username: {}", username);
            throw new UsernameNotFoundException("用户不存在: " + username);
        }
        log.info("User found: id={}, username={}", userEntity.getId(), userEntity.getUsername());


        List<String> rawPermissions  = userMapper.selectPermissionsByUserId(userEntity.getId());
        log.info("用户 '{}' (ID: {}) 从数据库查询到的原始权限/角色字符串: {}", userEntity.getUsername(), userEntity.getId(), rawPermissions);

        List<SimpleGrantedAuthority> authorities = rawPermissions.stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
        log.info("用户 '{}' 转换后的 GrantedAuthority 对象: {}", userEntity.getUsername(), authorities);

        boolean enabled = userEntity.getStatus() == 1;


        //返回自定义的 CustomUserDetails 对象，包含用户 ID
        return new CustomUserDetails(
                userEntity.getId(),
                userEntity.getUsername(),
                userEntity.getPassword(),
                enabled,
                true,
                true,
                true,
                authorities,
                rawPermissions
        );
    }
}
